import { useCallback, useContext, useRef } from 'react';
import { Search } from '../../../baseComponent';
import { BaseHelp, HelpContext, Table, TableSelectionModel } from '../../../functionalComponent';
import { Layout, iup, useRefCallback } from '../../../util';
import ProjectEngineeringTree from './ProjectEngineeringTree';
import { findFilterIndexes } from './utils';

const tableProps: any = {
  rowSelected: false,
  rowChecked: true,
  cache: false,
  headerMenu: false,
  style: { borderStyle: 'solid', borderColor: 'var(--border-color-split, #f0f0f0)', borderWidth: 1 }
};
const tableStyle: any = { borderStyle: 'solid', borderColor: 'var(--border-color-split, #f0f0f0)', borderWidth: 1 };
const { Header, Footer, MultipleButtons } = BaseHelp;

/**
 * 工程项目帮助content
 * @returns
 */
export function HelpContent() {
  const {
    request,
    ok,
    contentParams: {
      showTree = false,
      getFieldValue,
      columns,
      helpTitle,
      helpId,
      selectedArray,
      multiple,
      footer,
      treeProps
    },
    locale,
    randomKey
  } = useContext<any>(HelpContext);
  const btnRef = useRef<any>();

  const rightTable = useRef<any>();

  const MAIN_TABLE_KEY = `${helpId}_${randomKey}_main`;

  // 表格
  const getTable = useCallback((tableKey) => tableKey && iup.compIns[tableKey].getApi(), []);

  const getResult: any = () => {
    if (multiple) {
      const result = rightTable.current
        .getApi()
        .getRows()
        .map((r) => ({
          value: getFieldValue(r),
          label: getFieldValue(r, 'label'),
          origin: { ...r }
        }));
      return result.length > 0 ? result : undefined;
    } else {
      const value = getTable(MAIN_TABLE_KEY).getSelectedData()[0];
      if (value) {
        return { value: getFieldValue(value), label: getFieldValue(value, 'label'), origin: { ...value } };
      }
      return undefined;
    }
  };

  const toRight = (values: any) => {
    if (multiple) {
      btnRef.current.toRight(values);
    } else {
      ok(getResult());
    }
  };

  const onSearch = (value: string) => {
    getTable(MAIN_TABLE_KEY).query({ keyword: value });
  };

  // 默认选中
  const onDataLoad = useRefCallback((table) => {
    const { dataSource = [] } = table.getState() || {};
    const selectIndex = findFilterIndexes(dataSource, (it) => (selectedArray || []).map((x) => x.id).includes(it.id));
    table.setSelected(selectIndex);
  });

  return (
    <Layout>
      <Header title={helpTitle || '工程项目帮助'} />
      <Layout.Flex direction="row" style={{ padding: 5 }}>
        {showTree && (
          <Layout.Slider size={240}>
            <ProjectEngineeringTree
              getTable={() => getTable(MAIN_TABLE_KEY)}
              multiple={multiple}
              treeProps={treeProps}
              showTree={showTree}
            />
          </Layout.Slider>
        )}
        <Layout.Flex direction="column" style={{ marginLeft: 8 }}>
          <Search
            size="small"
            allowClear
            placeholder={locale.searchPlaceholder}
            onSearch={onSearch}
            style={{ marginBottom: 8, width: 300, alignSelf: 'flex-end' }}
          />
          <Layout.Flex direction="column">
            <Layout.Flex>
              <Table
                style={tableStyle}
                id={MAIN_TABLE_KEY}
                columns={columns}
                pagination={{ hideOnSinglePage: false }}
                autoLoad={true}
                request={request}
                response={(res) => ({ total: res.total ?? 0, record: res.list || [] })}
                rowSelection={{
                  type: multiple
                    ? [TableSelectionModel.CHECKBOX, TableSelectionModel.MULTIPLE_INTERVAL]
                    : TableSelectionModel.ROW
                }}
                onRow={(rowIndex, table) => ({
                  onDoubleClick: () => toRight([table.getRow(rowIndex)])
                })}
                onDataLoad={onDataLoad}
              />
            </Layout.Flex>
          </Layout.Flex>
        </Layout.Flex>
        {multiple && (
          <MultipleButtons
            getRowKey={getFieldValue}
            outRef={btnRef}
            getActiveTable={() => getTable(MAIN_TABLE_KEY)}
            getResultTable={() => rightTable.current.getApi()}
          />
        )}
        {multiple && (
          <Layout.Slider size={200}>
            <Table
              {...tableProps}
              columns={columns}
              dataSource={selectedArray}
              ref={rightTable}
              onRow={(rowIndex) => ({
                onDoubleClick: () => btnRef.current.toLeft(rowIndex)
              })}
            />
          </Layout.Slider>
        )}
      </Layout.Flex>
      <Footer getResult={getResult}>{footer && <span style={{ flex: 1, width: 0 }} children={footer} />}</Footer>
    </Layout>
  );
}
